import { getEnv } from '../utils/env';

// 数据库配置接口
export interface DatabaseConfig {
  host: string;
  port: number;
  username: string;
  password: string;
  database: string;
  dialect: 'mysql' | 'postgres' | 'sqlite' | 'mariadb' | 'mssql';
  pool?: {
    max: number;
    min: number;
    acquire: number;
    idle: number;
  };
  logging?: boolean;
  timezone?: string;
}

// 从环境变量读取数据库配置
export const databaseConfig: DatabaseConfig = {
  host: getEnv('DB_HOST'),
  port: getEnv('DB_PORT'),
  username: getEnv('DB_USERNAME'),
  password: getEnv('DB_PASSWORD'),
  database: getEnv('DB_NAME'),
  dialect: getEnv('DB_DIALECT'),
  pool: {
    max: getEnv('DB_POOL_MAX'),
    min: getEnv('DB_POOL_MIN'),
    acquire: getEnv('DB_POOL_ACQUIRE'),
    idle: getEnv('DB_POOL_IDLE')
  },
  logging: getEnv('DB_LOGGING'),
  timezone: getEnv('DB_TIMEZONE')
};

// 获取数据库连接字符串
export function getDatabaseUrl(): string {
  return `${databaseConfig.dialect}://${databaseConfig.username}:${databaseConfig.password}@${databaseConfig.host}:${databaseConfig.port}/${databaseConfig.database}`;
}

// 验证数据库配置
export function validateDatabaseConfig(): boolean {
  const required = ['host', 'username', 'password', 'database'];
  for (const field of required) {
    if (!databaseConfig[field as keyof DatabaseConfig]) {
      console.error(`数据库配置错误: 缺少必需的字段 ${field}`);
      return false;
    }
  }
  return true;
} 